package com.example.ivideo_2211a.fabu

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.VideoDetailActivity

import androidx.fragment.app.viewModels

class PublishVideoFragment : Fragment() {
    private lateinit var adapter: VideoListAdapter
    private val selectedVideos = mutableSetOf<VideoFaEntityItem>()
    private val viewModel by viewModels<PublishVideoViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_publish_video, container, false)
        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
        view.findViewById<View>(R.id.iv_back)?.setOnClickListener {
            requireActivity().supportFragmentManager.popBackStack()
        }
        adapter = VideoListAdapter(
            onCheckedChange = { video, checked ->
                if (checked) selectedVideos.add(video) else selectedVideos.remove(video)
            },
            onItemClick = { video ->
                // 跳转到视频详情页
                val intent = Intent(requireContext(), VideoDetailActivity::class.java)
                intent.putExtra("videoId", video.videoId)
                startActivity(intent)
            }
        )
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = adapter
        view.findViewById<View>(R.id.btn_publish).setOnClickListener {
            if (selectedVideos.isNotEmpty()) {
                Toast.makeText(requireContext(), "发布成功", Toast.LENGTH_SHORT).show()
                selectedVideos.clear()
                adapter.clearSelection()
            } else {
                Toast.makeText(requireContext(), "请先选择视频", Toast.LENGTH_SHORT).show()
            }
        }
    observeViewModel()
    viewModel.sendIntent(PublishVideoIntent.FetchVideoList)
        return view
    }

    private fun observeViewModel() {
        lifecycleScope.launchWhenStarted {
            viewModel.viewState.collect { state ->
                when (state) {
                    is PublishVideoViewState.VideoList -> adapter.submitList(state.list)
                    is PublishVideoViewState.Error -> Toast.makeText(requireContext(), state.error, Toast.LENGTH_LONG).show()
                    else -> {}
                }
            }
        }
    }


}
